import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { format, subDays } from 'date-fns';
import { CommonService } from '../../../../services-common/common.service';
import { divideConsumeStatusArrs } from '../../status.pipe';
import { PromotionIncomeManageService } from '../promotion-income-manage.service';

@Component({
  selector: 'app-promotion-income-consume',
  templateUrl: './promotion-income-consume.component.html',
  styleUrls: ['./promotion-income-consume.component.scss']
})
export class PromotionIncomeConsumeComponent implements OnInit {

  searchOptions: any = [
    {
      type: 2,
      labelText: '应用搜索',
      valueKey: 'appId',
      placeholder: '应用名称',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: []
    },
    { type: 1, labelText: '交易搜索', valueKey: 'orderNo', value: '', placeholder: '订单号/交易流水' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'state',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...divideConsumeStatusArrs]
    },
    {
      type: 2,
      labelText: '渠道',
      valueKey: 'walletId',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'content', label: 'name' },
      selectOptions: []
    },
    { type: 3, labelText: '发生时间', valueKey: ['beginTime', 'stopTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  gameOptions: any[] = []; // 应用options
  channelOptions: any[] = []; // 渠道options
  statisticsData: any = {
    sumAmount: '', // 总金额
    number: '' // 订单数
  }; // 统计

  exportLoading = false;

  constructor(
    private msg: NzMessageService,
    private modal: NzModalService,
    private commonService: CommonService,
    private services: PromotionIncomeManageService
  ) { }

  ngOnInit(): void {
    this.loadGameList();
    this.loadChannelOptionsData();
    this.resetDefaultTime();
  }

  // Search Options Set Value
  searchSetup(keyStr: string, options: any) {
    let objIndex = this.searchOptions.findIndex((item: any) => item.valueKey === keyStr);
    this.searchOptions[objIndex].selectOptions = options || [];
  }

  // 游戏渠道options
  async loadChannelOptionsData() {
    this.channelOptions = await this.commonService.getDictList('h5game_channel');
    this.searchSetup('walletId', this.channelOptions);
  }

  // 查询应用列表
  async loadGameList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.services.getGameList(params);
    
    if (code === 0) {
      this.gameOptions = data.records || [];
      this.setSearchOption(this.gameOptions, 'appId');
    } else {
      this.msg.error(message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      changeType: 2, // 变更方式 1.充值 2.消费
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getRechargeConsumptionList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      console.log('充值记录data', data);
      const {records, total} = data.list || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;

      for (let key in this.statisticsData) {
        this.statisticsData[key] = !this.commonService.isEmpty(data[key]) ? data[key] : '';
      }
    } else {
      this.msg.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.resetDefaultTime();
    params.beginTime = format(subDays(new Date(), 7), 'yyyy-MM-dd');
    params.stopTime = format(new Date(), 'yyyy-MM-dd');

    this.searchParams = params;
    this.searchParams.changeType = 2; // 变更方式 1.充值 2.消费
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {    
        let params = {
          ...this.searchParams,
          changeType: 2, // 变更方式 1.充值 2.消费
        }
        this.exportLoading = true;
        const res: any = await this.services.exportRechargeConsumption(params);
        this.exportLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '推广分成消费记录');
        } else {
          this.msg.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  setDefaultTime(dyaNum: number) {
    return [format(subDays(new Date(), dyaNum), 'yyyy-MM-dd'), format(new Date(), 'yyyy-MM-dd')];
  }

  resetDefaultTime() {
    let setIndex = this.searchOptions.findIndex((ele: any) => ele.labelText === '发生时间');
    this.searchOptions[setIndex].value = this.setDefaultTime(7);
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }
}
